import {

  Message
} from 'element-ui'
import {
  login,
  getInfo
} from '@/api/user'
import {
  getToken,
  setToken,
  removeToken,
  getSuperUserToken,
  removeSuperUserToken
} from '@/utils/auth'
import router, {
  resetRouter
} from '@/router'
import {
  getCount
} from "@/api/message";
import {
  Base64
} from '@/utils/index.js' // get token from cookie

import {
  getEnterpriseById
} from "../../api/wastecomponey.js";
const state = {
  superUserObj: getSuperUserToken(),
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  userObj: {},
  count: 0
}

const mutations = {
  SET_COUNT: (state, count) => {
    state.count = count
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_USEROBJ: (state, userObj) => {
    state.userObj = userObj
  }
}

const actions = {
  getCount({
    commit
  }) {
    return new Promise((resolve, reject) => {
      getCount().then(response => {
        console.log(response)
        const {
          data
        } = response
        commit('SET_COUNT', data)
        resolve()
      }).catch(error => {
        console.log(error)
        reject(error)
      })
    })
  },
  // user login
  login({
    commit
  }, userInfo) {
    const {
      phone,
      password,
      clientType,
      orgGuid
    } = userInfo


    return new Promise((resolve, reject) => {
      login({
        phone: phone.trim(),
        password: password,
        clientType: clientType,
        orgGuid: orgGuid
      }).then(response => {
        console.log(response)
        if (!response.success) {
          Message({
            message: response.msg,
            type: 'error',
            duration: 5 * 1000
          })
        }
        const {
          token
        } = response
        commit('SET_TOKEN', token.access_token)
        setToken(token.access_token)
        resolve()
      }).catch(error => {
        console.log(error)
        reject(error)
      })
    })
  },

  // get user info
  getInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      let orgid = ''
      if (state.superUserObj != null && state.superUserObj != undefined && state.superUserObj.orgGuid !=
        undefined) {

        orgid = state.superUserObj.orgGuid
      }
      let params = {
        "OrgGuid": orgid
      }

      getInfo(params).then(response => {
        // console.log(response)
        const {
          data,
          data2
        } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const {
          roleId,
          name,
          headPortraitUrl,
          orgGuid
        } = data
        // data.areaNumber = data2.areaNumber;
        data.areaNumber = "45";
        let base = new Base64();

        data.areaNumberStr = base.encode(data.areaNumber + '|' + name);

        // roles must be a non-empty array
        if (!roleId) {
          reject('getInfo: roles must be a non-null array!')
        }

        commit('SET_ROLES', roleId)
        commit('SET_NAME', name)
        commit('SET_AVATAR', headPortraitUrl)
        getEnterpriseById(orgGuid).then(response => {
          const conmany = response.data;
          data.orgName = conmany.name
          data.inviteCode = conmany.inviteCode
          commit('SET_USEROBJ', data)



          resolve(data)
        })
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({
    commit,
    state,
    dispatch
  }) {
    commit('SET_TOKEN', '')
    commit('SET_ROLES', [])
    commit('SET_USEROBJ', {})
    removeToken()
    resetRouter()

    // reset visited views and cached views
    // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
    dispatch('tagsView/delAllViews', null, {
      root: true
    })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_USEROBJ', {})
      removeSuperUserToken()
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({
    commit,
    dispatch
  }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const {
      roles
    } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, {
      root: true
    })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, {
      root: true
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
